package com.dongdong.shiro;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdong.exception.LoginException;
import com.dongdong.pojo.TbSeller;
import com.dongdong.pojo.TbUser;
import com.dongdong.service.SellerService;
import com.dongdong.service.UserService;
import com.dongdong.util.ShiroUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;


public class LoginRealm extends AuthorizingRealm {
    @Reference(timeout = 50000)
    private UserService userService;
   //授权逻辑的方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权方法");
        //根据登录用户查询数据库，看数据库中是否有该权限字符串
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //从数据库 查询 权限字符串
       /* TPerson person = (TPerson)SecurityUtils.getSubject().getPrincipal();*/
        //根据登录id查询用户所拥有的字符串
        return info;
    }
    //编写认证逻辑的方法（登录）
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        TbUser user = userService.selectByNname(token.getUsername());
        //查询账号信息
        if (user == null){
            throw new UnknownAccountException("账号未注册");
        }
        String userName = user.getUsername();
        //2. 验证账号:
        if(!token.getUsername().equals(userName)){
            //账号不存在
            return null;
        }
        //参数位置 1 , 登录后的用户对象。2,3:数据库查询出来的用户名和密码
        return new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),user.getUsername());
    }

}
